<template>
  <el-dialog
    title="分配角色"
    :visible.sync="dialogVisibleAuth"
    :before-close="closedDialog"
  >
    <el-form v-if="userInfo" :model="userInfo">
      <el-form-item label="用户名" :label-width="formLabelWidth">
        {{ userInfo.username }}
      </el-form-item>
      <el-form-item label="角色" :label-width="formLabelWidth">
        <el-select placeholder="" v-model="roleId">
          <el-option label="请选择" :value="-1" disabled></el-option>

          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closedDialog">取 消</el-button>
      <el-button type="primary" @click="submitDialog">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    dialogVisibleAuth: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default() {
        return {
          // 默认选择 “请选择”
          role_name: -1
        }
      }
    }
  },
  data() {
    return {
      formLabelWidth: '120px',
      rolesList: [],
      roleId: -1
    }
  },
  watch: {
    dialogVisibleAuth(val) {
      if (val) {
        this.getRolesList()
        this.getUserInfo()
      }
    }
  },
  methods: {
    // 获取用户 角色id 信息
    async getUserInfo() {
      const { data } = await this.$http.get(`/users/${this.userInfo.id}`)
      const { meta, data: roleData } = data
      if (meta.status === 200) {
        this.roleId = roleData.rid
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 获取角色列表
    async getRolesList() {
      const { data } = await this.$http.get('/roles')
      const { meta, data: rolesData } = data
      if (meta.status === 200) {
        this.rolesList = rolesData
      } else {
        this.$message.error(meta.msg)
      }
    },
    closedDialog() {
      // this.$parent.$data.dialogVisibleAuth = false
      this.$emit('authUserClosed')
    },
    // 提交修改
    async submitDialog() {
      const { id } = this.userInfo

      const {
        data: { meta }
      } = await this.$http.put(`users/${id}/role`, {
        rid: this.roleId
      })

      if (meta.status === 200) {
        // 添加成功后，关闭对话框，更新 users 页码表格数据
        this.$message.success(meta.msg)
        // this.$parent.$data.dialogVisibleAuth = false
        this.$emit('authUserClosed')
        this.$emit('authUserSuccess')
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style></style>
